// pages/Record/Record.js
const App = getApp();
const server = App.path.Server
const uid = App.globalData.uid;

Page({

    /**
     * 页面的初始数据
     */
    data: {
        config: {},
        origin: '', // 来自哪个页面。查访()，护理()，家政()，体检()
        key: '', // 老人唯一标识
        images: [ //存放用于渲染的图片数组
            // {
            //     uploaded: false, // 是否上传完成 用于显示loading
            //     file: e.tempFilePaths[0] // 文件地址
            // }
        ],
        imageList: [], // 用于存放要发送给服务器的图片id
        defaultImages: '/images/add.png',
        iconClose: '/images/x_b.png',
        result: '0', // 选项结果
        status: [ // 选项选择渲染数据
            {
                title: '正常记录',
                key: 'normal',
                value: '0',
                checked: true
            }, {
                title: '异常记录',
                key: 'error',
                value: '1',
                checked: false
            }
        ],
        textarea:'',
        id: '',
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData(options)
        // console.log(typeof this.data.id )
        // console.log(typeof this.data.id !== 'null')
        if(this.data.id !== null && this.data.id !== 'null') {
            this.getPageConfig()
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

    // 图片选择
    imageSelectUpload() {
        if(this.data.id === 'null' || this.data.id === null) {
            const that = this;
            wx.chooseImage({
                count: 1,
                sizeType: 'compressed',
                success(e) {
                    if (that.data.images && that.data.images.length < 9) {
                        let temp = that.data.images
                        let file = {
                            uploaded: false,
                            file: e.tempFilePaths[0]
                        }
                        temp.push(file)
                        that.setData({
                            images: temp
                        })

                        that.imageUpload(e.tempFilePaths[0], that.data.images.length - 1)
                    }
                },
                fail(e) {
                    // console.log('选择图片失败')
                    console.log(e)
                    // wx.showModal({
                    //     title: '选择图片失败，请重试',
                    //     content: e,
                    //     showCancel: false
                    // })
                }
            })
        }
    },

    // 图片上传
    imageUpload(address, index) {
        let that = this
        wx.uploadFile({
            url: server + '/v1/file/upload',
            filePath: address,
            name: 'file',
            success(res) {
                let temp = that.data.images
                let list = that.data.imageList
                temp[index].uploaded = true
                list.push(res.data)
                that.setData({
                    images: temp,
                    imageList: list
                })
            },
            fail(res){
                wx.showModal({
                    title: '上传失败',
                    content: '网络超时，请重试',
                    showCancel: false
                })
                let temp = that.data.images
                temp.splice(index, 1)
                that.setData({
                    images: temp
                })
            }
        })
    },

    // radio改变
    radioChange(e) {
        this.setData({
            result: e.detail.value
        })
    },

    // 删除图片
    deleteImage(e) {
        let index = e.target.dataset.index
        let temp = this.data.images
        let list = this.data.imageList
        temp.splice(index, 1)
        list.splice(index, 1)
        this.setData({
            images: temp,
            imageList: list
        })
    },

    submit(e) {
        if(this.data.id === 'null'){
            let images = this.data.images
            let needWait = false
            images.map((img) => {
                if (!img.uploaded) {
                    needWait = true
                }
            })
            if (!needWait) {
                if (this.data.textarea === '') {
                    wx.showModal({
                        title: '提交出错',
                        content: '请输入老人当前状态',
                        showCancel: false
                    })
                }
                else {
                    let pages = getCurrentPages()
                    let length = pages.length
                    let visit = pages[length - 2]
                    let list = this.data.imageList
                    let listStr = list.join(',')
                    // console.log(encodeURIComponent(listStr))
                    visit._setPhotosToData(this.data.page, {
                        images: listStr,
                        oldmanState: this.data.result,
                        remark: this.data.textarea
                    })
                    wx.navigateBack()
                }
            }
            else {
                wx.showModal({
                    title: '提交错误',
                    content: '请等待图片上传完成',
                    showCancel: false
                })
            }
        }
    },

    // 设置textarea内容
    setInput(e){
        // console.log(e)
        this.setData({
            textarea: e.detail.value
        })
    },

    // 获取页面信息
    getPageConfig(){
        const _this = this
        wx.request({
            url: server + '/v1/order/getSubDetail/' + _this.data.id,
            header: {
              'Authorization': 'Bearer ' + App.globalData.token.access_token
            },
            complete(res){
                // console.log(res)
                App.judgeCode(res, function(_res){
                    let images = _res.data.images.split(',')
                    let array = _this.data.images
                    images.map((item)=>{
                        array.push({
                            uploaded: true, // 是否上传完成 用于显示loading
                            file: item // 文件地址
                        })
                    })
                    let stutas = _this.data.status
                    if (_res.data.oldmanState === 0){
                        stutas[0].checked = true
                        stutas[1].checked = false
                    }
                    else{
                        stutas[0].checked = false
                        stutas[1].checked = true
                    }
                    _this.setData({
                        config: _res.data,
                        images: array,
                        textarea: _res.data.remark,
                        result: _res.data.oldmanState
                    })
                })
            }
        })
    }
})